package org.example.datastructure.ch2;

import java.util.ArrayList;
import java.util.List;

public class Poly {
    List<Node> nodes = new ArrayList<>();
    public Poly(List<Node> nodes) {
        this.nodes = nodes;
    }
    public Poly add(Poly other) {
        int len1 = this.nodes.size();
        int len2 = other.nodes.size();
        int len = Math.max(len1,len2);
        List<Node> res = new ArrayList<>();
        int i1 = 0;
        int i2 = 0;
        while(i1<len1&&i2<len2){
            Node t = new Node();
            Node n1 = this.nodes.get(i1);
            Node n2 = other.nodes.get(i2);
            if(n1.exp==n2.exp){
                t.coff = n1.coff+n2.coff;
                t.exp = n1.exp;
                i1++;
                i2++;
            }
            else if(n1.exp>n2.exp){
                t.coff = n1.coff;
                t.exp = n1.exp;
                i1++;
            }
            else{
                t.coff = n2.coff;
                t.exp = n2.exp;
                i2++;
            }
            res.add(t);
            }
        while(i1<len1){
            Node t = new Node();
            t.coff = this.nodes.get(i1).coff;
            t.exp = this.nodes.get(i1).exp;
            res.add(t);
            i1++;
        }
        while(i2<len2){
            Node t = new Node();
            t.coff = other.nodes.get(i2).coff;
            t.exp = other.nodes.get(i2).exp;
            res.add(t);
            i2++;
        }
        return new Poly(res);

    }
    public void print(){
        for(Node n:nodes){
            System.out.print(n.coff+"x^"+n.exp+" + ");
        }
    }

}

